<?php
/**
 * Author: yann
 * QQ: 9197313
 * Date: 2018/12/14 0014
 * Time: 下午 3:11
 */

namespace app\admin\controller;

use app\model\Menu as _Menu;
use app\util\ReturnCode;

class Menu extends Base
{

    protected $menu;

    public function __construct(_Menu $menu)
    {
        parent::__construct();
        $this->menu = &$menu;
    }

    /**
     * 菜单列表
     * @return false|string
     */
    public function index(){
        $list = $this->menu->getList();
        return $this->buildSuccess(['list'=>$list]);
    }

    /**
     * 新增菜单
     * @return false|string
     */
    public function add() {
        $postData = $this->request->post();
        if ($postData['url'])
            $postData['url'] = 'admin/' . $postData['url'];

        if ($this->menu->insert($postData))
            return $this->buildSuccess([]);
        else
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
    }

    /**
     * 编辑菜单状态
     * @return false|string
     */
    public function changeStatus() {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        if(!$id)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '参数错误');

        if ($this->menu->allowField(true)->save(['hide'=>$status],['id'=>$id]))
            return $this->buildSuccess([]);
        else
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
    }

    /**
     * 编辑菜单
     * @return false|string
     */
    public function edit() {
        $postData = $this->request->post();
        if ($postData['url'])
            $postData['url'] = 'admin/' . $postData['url'];

        $id = $this->request->post('id');
        if ($this->menu->allowField(true)->save($postData,['id'=>$id]))
            return $this->buildSuccess([]);
        else
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
    }

    /**
     * 
     * 删除菜单
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del() {
        $id = $this->request->post('id');
        if (!$id)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '参数错误');

        if ($this->menu->where(['fid' => $id])->count()) {
            return $this->buildFailed(ReturnCode::INVALID, '当前菜单存在子菜单,不可以被删除!');
        } else {
            $this->menu->where(['id'=>$id])->delete();
            return $this->buildSuccess([]);
        }
    }

}
